package com.baseweb.webadmin.controller.admin;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.ByUserBizProductBvo;
import com.baseweb.webadmin.core.model.bvo.UserInfoBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.MD5Util;
import com.baseweb.webadmin.core.util.ObjectFormatter;
import com.baseweb.webadmin.core.util.RandCharUtil;
import com.baseweb.webadmin.core.util.UploadUtil;
import com.baseweb.webadmin.service.ContentService;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/product")
public class ProductController extends BaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContentService contentService;

    private String prefix = "/product";

    @RequestMapping(value = "/addPackageView")
    public String addPackageView(@RequestParam(value = "id",required = false) Integer id,
                                Model model) {

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        return prefix + "/addPackageView";
    }

    @RequestMapping(value = "/editPackageView")
    public String editPackageView(@RequestParam(value = "id",required = false) Integer id,
                                 Model model) {

        if (id != null && id > 0){
            model.addAttribute("bizPackage", userService.findBizPackage(id));
        }

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        return prefix + "/editPackageView";
    }

    @RequestMapping(value = "/submitPackage")
    public String submitPackage(@RequestParam(value = "id",required = false) Integer id,
                               @RequestParam(value = "user_id",required = false) Integer user_id,
                               @RequestParam(value = "name",required = false) String name,
                               @RequestParam(value = "status",defaultValue = "-1") Integer status,
                               Model model) {
        try{
            ByUserBizPackage byUserBizPackage = null;
            if (id != null && id > 0){
                byUserBizPackage = userService.findBizPackage(id);
            }else{
                byUserBizPackage = new ByUserBizPackage();
            }

//            User user = getCurrentUser();
            byUserBizPackage.setUserId(user_id);
            byUserBizPackage.setName(name);
            byUserBizPackage.setStatus(status);
            byUserBizPackage.setCreateTime(new DateTime());
            byUserBizPackage.setUpdateTime(new DateTime());

            userService.insertBizPackage(byUserBizPackage);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return prefix + "/packageManage";
    }

    //服务,套餐
    @RequestMapping(value = "/packageManage")
    public String packageManage() {
        return prefix + "/packageManage";
    }

    @RequestMapping(value = "/getPackageList")
    public void getPackageList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                               @RequestParam(value = "user_id", required = false) Integer user_id,
                               @RequestParam(value = "name", required = false) String name,
                               Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        List<ByUserBizPackage> list = userService.selectPackageListByPage(user_id, name,(page-1)*pageSize, pageSize);
        int total = userService.selectPackageListCount(user_id, name);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    @RequestMapping(value = "/myPackage")
    public String myPackage() {
        return prefix + "/myPackage";
    }

    @RequestMapping(value = "/getMyPackageList")
    public void getMyPackageList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                 @RequestParam(value = "name",required = false) String name,
                                 Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByUserBizPackage> list = userService.selectPackageListByPage(user.getId(), name,(page-1)*pageSize, pageSize);
        int total = userService.selectPackageListCount(user.getId(), name);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }


    @RequestMapping(value = "/addPackageDetailView")
    public String addPackageDetailView(@RequestParam(value = "package_id",required = false) Integer package_id,
                                       Model model) {

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        model.addAttribute("package_id", package_id);
        return prefix + "/addPackageDetailView";
    }

    @RequestMapping(value = "/editPackageDetailView")
    public String editPackageDetailView(@RequestParam(value = "id",required = false) Integer id,
                                        Model model) {

        if (id != null && id > 0){
            model.addAttribute("bizPackageDetail", userService.findBizPackageDetail(id));
        }

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        return prefix + "/editPackageDetailView";
    }

    @RequestMapping(value = "/submitPackageDetail")
    public String submitVerify(@RequestParam(value = "id",required = false) Integer id,
                               @RequestParam(value = "user_id",required = false) Integer user_id,
                               @RequestParam(value = "package_id",required = false) Integer package_id,
                               @RequestParam(value = "product_id",required = false) Integer product_id,
                               @RequestParam(value = "status",defaultValue = "-1") Integer status,
                               Model model) {
        try{
            ByUserBizPackageDetail byUserBizPackageDetail = null;
            if (id != null && id > 0){
                byUserBizPackageDetail = userService.findBizPackageDetail(id);
            }else{
                byUserBizPackageDetail = new ByUserBizPackageDetail();
            }

//            User user = getCurrentUser();
            byUserBizPackageDetail.setUserId(user_id);
            byUserBizPackageDetail.setPackageId(package_id);
            byUserBizPackageDetail.setProductId(product_id);
            byUserBizPackageDetail.setStatus(status);
            byUserBizPackageDetail.setCreateTime(new DateTime());
            byUserBizPackageDetail.setUpdateTime(new DateTime());

            userService.insertBizPackageDetail(byUserBizPackageDetail);
            model.addAttribute("result", true);
            model.addAttribute("package_id", package_id);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return prefix + "/packageDetailManage";
    }

    @RequestMapping(value = "/packageDetailManage")
    public String packageDetailManage(@RequestParam(value = "package_id", required = false) Integer package_id,
                                      Model model) {
        model.addAttribute("package_id", package_id);

        return prefix + "/packageDetailManage";
    }

    @RequestMapping(value = "/getPackageDetailList")
    public void getPackageDetailList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                     @RequestParam(value = "user_id",required = false) Integer user_id,
                                     @RequestParam(value = "package_id", required = false) Integer package_id,
                                     @RequestParam(value = "product_id",required = false) Integer product_id,
                                     Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

//        User user = getCurrentUser();
        List<ByUserBizPackageDetail> list = userService.selectPackageDetailListByPage(user_id, package_id, product_id,(page-1)*pageSize, pageSize);
        int total = userService.selectPackageDetailListCount(user_id, package_id, product_id);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }



    //Product
    @RequestMapping(value = "/addProductView")
    public String addProductView(@RequestParam(value = "id",required = false) Integer id,
                                Model model) {

        model.addAttribute("productTypeList", AuthType.getAllData());

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }
//        model.addAttribute("user", getCurrentUser());
        return prefix + "/addProductView";
    }

    @RequestMapping(value = "/editProductView")
    public String editProductView(@RequestParam(value = "id",required = false) Integer id,
                                 Model model) {

        if (id != null && id > 0){
            model.addAttribute("bizProduct", userService.findBizProduct(id));
        }

        boolean is_writable = true;

        User user = getCurrentUser();
        List<Role> userRoles = roleService.selectRoleListByUser(user.getId().toString());

        for(Role current : userRoles) {
            if ((current.getId().intValue() == RoleType.NORMAL_BIZ.getCode())
                    || (current.getId().intValue() == RoleType.NORMAL_USER.getCode()))
            {
                is_writable = false;
                break;
            }
        }

        if (is_writable){
            model.addAttribute("is_writable", is_writable);
        }

        model.addAttribute("productTypeList", AuthType.getAllData());

        return prefix + "/editProductView";
    }

    @RequestMapping(value = "/submitProduct")
    public String submitProduct(@RequestParam(value = "id",required = false) Integer id,
                               @RequestParam(value = "user_id",required = false) Integer user_id,
                               @RequestParam(value = "file",required = false) MultipartFile file,
                               @RequestParam(value = "name",required = false) String name,
                               @RequestParam(value = "descn",required = false) String descn,
                               @RequestParam(value = "product_type",required = false) Integer product_type,
                                @RequestParam(value = "original_price",required = false) String original_price,
                                @RequestParam(value = "current_price",required = false) String current_price,
                                @RequestParam(value = "coins",defaultValue = "0") Integer coins,
                                @RequestParam(value = "unit",required = false) String unit,
                                @RequestParam(value = "deposit",required = false) String deposit,
                               @RequestParam(value = "status",defaultValue = "-1") Integer status,
                               Model model) {
        try{
            ByUserBizProduct byUserBizProduct = null;
            if (id != null && id > 0){
                byUserBizProduct = userService.findBizProduct(id);
            }else{
                byUserBizProduct = new ByUserBizProduct();
            }

            User user = getCurrentUser();
            if (user_id !=null && user_id > 0) {
                byUserBizProduct.setUserId(user_id);
            }else{
                byUserBizProduct.setUserId(user.getId());
            }
            byUserBizProduct.setName(name);
            byUserBizProduct.setDescn(descn);
            byUserBizProduct.setStatus(status);
            byUserBizProduct.setProductType(product_type);
            byUserBizProduct.setChannelId(user.getBizWorkType());
            byUserBizProduct.setOriginalPrice(ObjectFormatter.str2BigDecimal(original_price));
            byUserBizProduct.setCurrentPrice(ObjectFormatter.str2BigDecimal(current_price));
            byUserBizProduct.setCoins(coins);
            byUserBizProduct.setUnit(unit);
            byUserBizProduct.setDeposit(ObjectFormatter.str2BigDecimal(current_price).multiply(Constants.PRODUCT_DEPOSIT_RATIO));
            byUserBizProduct.setCreateTime(new DateTime());
            byUserBizProduct.setUpdateTime(new DateTime());

            if (file != null && file.getSize() > 0){
                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

//                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
                UploadUtil.uploadData(file.getBytes(), img_url);
                byUserBizProduct.setImgUrl(img_url);
            }

            userService.insertBizProduct(byUserBizProduct);
            model.addAttribute("result", true);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("result", false);
        }
        return prefix + "/myProduct";
    }

    @RequestMapping(value = "/productManage")
    public String productManage() {
        return prefix + "/productManage";
    }

    @RequestMapping(value = "/getProductList")
    public void getProductList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                               @RequestParam(value = "user_id", required = false) Integer user_id,
                               @RequestParam(value = "product_type", required = false) Integer product_type,
                               @RequestParam(value = "channel_id", required = false) Integer channel_id,
                               Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        List<ByUserBizProductBvo> list = new ArrayList<ByUserBizProductBvo>();
        List<ByUserBizProduct> byUserBizProducts = userService.selectProductListByPage(user_id, product_type, channel_id,(page-1)*pageSize, pageSize,
                                                                    null, null, null, null);

        if (byUserBizProducts != null && byUserBizProducts.size() > 0){
            for (ByUserBizProduct current : byUserBizProducts){
                User currentUser = userService.selectUserById(current.getUserId());
                list.add(ByUserBizProductBvo.copyFrom(current, UserInfoBvo.copyFrom(currentUser,null, contentService.findChannel(currentUser.getBizWorkType()))));
            }
        }

        int total = userService.selectProductListCount(user_id, product_type, channel_id,
                null, null, null, null);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    @RequestMapping(value = "/myProduct")
    public String myProduct() {
        return prefix + "/myProduct";
    }

    @RequestMapping(value = "/getMyProductList")
    public void getMyProductList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                 @RequestParam(value = "product_type", required = false) Integer product_type,
                                 @RequestParam(value = "channel_id", required = false) Integer channel_id,
                                 Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        User user = getCurrentUser();
        List<ByUserBizProduct> list = userService.selectProductListByPage(user.getId(), product_type, channel_id,(page-1)*pageSize, pageSize,
                null, null, null, null);
        int total = userService.selectProductListCount(user.getId(), product_type, channel_id,
                null, null, null, null);
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);
    }

    @RequestMapping(value = "/passProductView")
    public String passProductView(@RequestParam(value = "id",required = true) Integer id,
                                 @RequestParam(value = "status",defaultValue = "1") Integer status,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                 Model model) {

        ByUserBizProduct byUserBizProduct = null;
        if (id != null && id > 0){
            byUserBizProduct = userService.findBizProduct(id);

            if (status == BaseState.NORMAL.getCode()){
                User user = userService.selectUserById(byUserBizProduct.getUserId());
                if (user != null){
                    user.setBizPrice(byUserBizProduct.getCurrentPrice());
                    userService.updateUser(user);
                }
            }

            byUserBizProduct.setStatus(status);

            userService.insertBizProduct(byUserBizProduct);
        }

        String pathUrl = request.getHeader("referer");
        if (StringUtils.isNotBlank(pathUrl) && pathUrl.indexOf("myProduct") != -1){
            return prefix + "/myProduct";
        }else{
            return prefix + "/productManage";
        }
    }

}
